import axios from "axios"
import { showToast } from 'vant'
import { Base64 } from "js-base64"
import useUserStore from "@/stores/useUserStore.js"
import emitter from "@/utils/mitt.js"

const request = axios.create({
  baseURL: 'https://meituan.thexxdd.cn/apie'
})

request.interceptors.request.use((config) => {
  const userStore = useUserStore()
  if (userStore.user.user_Token) {
    let token = 'Basic ' + Base64.encode(userStore.user.user_Token + ':' + import.meta.env.VITE_ORDER_ID)
    config.headers.Authorization = token
  }
  return config
}, (err) => {
  return Promise.reject(err)
})

request.interceptors.response.use((res) => {
  return res.data
}, (err) => {
  const userStore = useUserStore()
  if (err.response.status === 401) {
    userStore.deleteUser()
    showToast({ message: err.response.data.msg, duration: 500 })
    emitter.emit('openLogin', { show: true })
  }
  return Promise.reject(err)
})

export default request